<script lang="ts" setup name="应急响应">
import { ref, reactive, computed, onMounted, h, watch } from "vue";
import ProFrom from "@/components/ProFrom/ProFrom.vue";
import ProTable from "@/components/ProTable";
import { levelFormMap, personFormMap } from "./form";
import { levelColumns, personColumns } from "./table";
import { setBaseApi, get, post, del } from "@/api/http";
import { useGlobalStore } from "@/stores";

const { getValByDictionary } = useGlobalStore();
// setBaseApi("/watch/staff/");

const queryForm = reactive({});
const querying = ref<boolean>(false);
const queryFormRef = ref<InstanceType<typeof ProFrom>>();

const tableData = reactive({
  levelList: [] as any,
  personList: [],
  personTotal: 0,
});

// 是否存在已开启的响应
const hadExitOpen = computed(() =>
  tableData.levelList.some((e: any) => e.responseStatus == 2)
);

const levelTableRef = ref<InstanceType<typeof ProTable>>();

const personTableRef = ref<InstanceType<typeof ProTable>>();

const selectedLevel = computed(
  () => levelTableRef.value?.selectedRowKeys[0] ?? tableData.levelList[0]?.id
);
const selectedPersonList = computed(
  () => personTableRef.value?.selectedRowKeys
);
watch(selectedLevel, (level) => getPeronList());

onMounted(() => getLevelList());

const getLevelList = () => {
  get("/watch/response/list").then((list) => {
    tableData.levelList = list;
    //tableRef.value?.updateTotal(totalCount)
  });
  getPeronList();
};
const getPeronList = () => {
  const responseId = selectedLevel.value;
  if (!responseId) return;
  get("/watch/people/getListByResponseId", { responseId }).then((list) => {
    tableData.personList = list.map((row: any) => ({
      ...row,
      ...row.watchStaffDto,
      id: row.id,
    }));
  });
};

// 级别 增删改
const levelFormRef = ref<InstanceType<typeof ProFrom>>();
const levelModel = reactive({
  open: false,
  editAble: true,
  title: "编辑",
  row: {} as any,
});

const onLevelEdit = () => {
  if (levelModel.title == "详情") return (levelModel.open = false);
  levelFormRef.value?.verify().then((data: any) => {
    const id = levelModel.row?.id;
    const params = { id, ...data };
    // console.log(params);
    post("/watch/response/saveOrUpdate", params, "提交")
      .then(() => {
        levelModel.open = false;
      })
      .finally(() => getLevelList());
  });
};

const handleLevelEdit = (row?: any) => {
  levelModel.open = true;
  levelModel.editAble = true;
  levelModel.title = row ? "编辑" : "新增";
  levelModel.row = row ?? {};
};
// const handleDetail = (row: any) => {
//   levelModel.open = true;
//   levelModel.editAble = false;
//   levelModel.title = "详情";
//   levelModel.row = row;
// };

// 切换响应状态
const onChangeStatus = (responseStatus: number, { id }: any) => {
  get("/watch/response/updateStatus", { id, responseStatus }, "响应状态更新");
};

// 人员增删改
const personFormRef = ref<InstanceType<typeof ProFrom>>();
const personModel = reactive({
  open: false,
  editAble: true,
  title: "编辑",
  row: {} as any,
});
const onPersonEdit = () => {
  // if (personModel.title == "详情") return (personModel.open = false);
  personFormRef.value?.verify().then((data: any) => {
    const responseId = selectedLevel.value;

    const params = { responseId, ...data };
    console.log(params);

    post("/watch/people/saveOrUpdate", params, "新增").then(() => {
      // return;
      getPeronList();
      personModel.open = false;
    });
  });
};

// 批量添加响应人员
// const batchAdd =reactive({
//   open:false,
//   names:'',
// })
// const batchAddPerson = () => {
//   const data = {
//     responseId: "1",
//     workingGroup: "应急协调组",
//     position: 3,
//     staffId: "90",
//   };
// };

const handlePersonEdit = (row?: any) => {
  personModel.open = true;
  personModel.editAble = true;
  personModel.title = row ? "编辑" : "新增";
  personModel.row = row ?? {};
};
const handleDelete = (row?: any) => {
  const ids = row?.id ? [row.id] : selectedPersonList.value;
  // console.log(ids);
  // return;
  del("/watch/people/delete", ids, "删除").then(() => {
    getPeronList();
  });
};
</script>

<template>
  <section class="page">
    <main class="grid grid-cols-2 gap-15px">
      <header>应急响应级别</header>
      <header>应急响应人员</header>
      <!-- 左侧级别列表 -->
      <div>
        <nav>
          <ProButton type="primary" text="应急预案" />

          <ProButton
            @click="getLevelList()"
            text="刷新"
            :loading="querying"
            icon="redoOutlined"
          />
        </nav>
        <ProTable
          ref="levelTableRef"
          :data="tableData.levelList"
          :columns="levelColumns"
          :operate="{
            编辑: handleLevelEdit,
            // 详情: handleDetail,
          }"
          selection="radio"
          @afterOperate="getLevelList"
        >
          <a-table-column title="响应状态" ellipsis align="center" tooltip>
            <template #default="{ record }">
              <a-tooltip
                placement="top"
                :title="
                  hadExitOpen && record.responseStatus == 1
                    ? '若要开启，请先关闭其他响应状态'
                    : ''
                "
              >
                <a-switch
                  @change="(val:number) => onChangeStatus(val, record)"
                  :disabled="hadExitOpen && record.responseStatus == 1"
                  v-model:checked="record.responseStatus"
                  :checkedValue="2"
                  checkedChildren="响应中"
                  :unCheckedValue="1"
                  unCheckedChildren="未启动"
                >
                </a-switch>
              </a-tooltip>
            </template>
          </a-table-column>
        </ProTable>
      </div>

      <!-- 右侧人员列表 -->
      <div>
        <nav>
          <ProButton
            @click="handlePersonEdit()"
            type="primary"
            text="新增"
            icon="plusOutlined"
          />

          <ProButton
            @click="handleDelete()"
            type="danger"
            text="删除"
            :disabled="!selectedPersonList?.length"
            icon="deleteOutlined"
          />
        </nav>

        <ProTable
          ref="personTableRef"
          :data="tableData.personList"
          :columns="personColumns"
          :operate="{
            删除: handleDelete,
          }"
          selection="checkbox"
          :total="tableData.personTotal"
          @afterOperate="getPeronList"
        >
        </ProTable>
      </div>
    </main>

    <!-- 级别编辑弹框 -->
    <a-modal
      centered
      destroyOnClose
      v-model:visible="levelModel.open"
      :title="levelModel.title"
      @ok="onLevelEdit"
      :okText="levelModel.editAble ? '提交' : '关闭'"
    >
      <ProFrom
        ref="levelFormRef"
        :mapping="levelFormMap"
        :model-value="levelModel.row"
        :readonly="!levelModel.editAble"
      >
        <template v-slot:header>
          <span class="text-18px"
            >{{
              getValByDictionary("responseLevel", levelModel.row)
            }}应急响应</span
          >
        </template>
      </ProFrom>
    </a-modal>

    <!-- 响应人员新增弹框 -->
    <a-modal
      centered
      destroyOnClose
      v-model:visible="personModel.open"
      :title="personModel.title"
      @ok="onPersonEdit"
      :okText="personModel.editAble ? '提交' : '关闭'"
    >
      <ProFrom
        ref="personFormRef"
        :mapping="personFormMap"
        :model-value="personModel.row"
        :readonly="!personModel.editAble"
      >
        <template v-slot:header>
          <!-- <a-form-item label="响应级别">
            <span
              >{{
                getValByDictionary("responseLevel", levelModel.row)
              }}应急响应</span
            >
          </a-form-item> -->
        </template>
      </ProFrom>
    </a-modal>
  </section>
</template>

<style lang="less" scoped>
.page {
  > main {
    padding: 0;
    flex: none;
    box-shadow: none;
    background: transparent;
    > * {
      padding: 15px;
      background-color: #fff;
    }
    > header {
      font-size: 20px;
      font-weight: bold;
      line-height: 30px;
    }
  }
}
</style>
